package cn.cjj.gulimall.cart.interceptor;

import cn.cjj.common.constant.AuthServerConstant;
import cn.cjj.common.constant.CartConstant;
import cn.cjj.common.vo.MemberResponseVo;
import cn.cjj.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author CuiJunJie
 * @create 2021/7/6-17:09
 */

@Component
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo user = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            user.setUserId(member.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 1) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.USER_COOKIE_NAME)) {
                    user.setUserKey(cookie.getValue());
                    user.setTempUser(true);
                }
            }
        }

        if (StringUtils.isEmpty(user.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            user.setUserKey(uuid);
        }

        threadLocal.set(user);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo user = threadLocal.get();

        if (!user.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.USER_COOKIE_NAME, user.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
